package com.aia.ilp.web.json;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.SessionAware;
import org.springframework.util.StringUtils;

import com.aia.ilp.domain.Cust;
import com.aia.ilp.service.MainService;
import com.cfh.ahead.Constant;
import com.cfh.util.Tools;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class CustomerRegJson extends ActionSupport implements ModelDriven<Cust>, SessionAware {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CustomerRegJson.class);

	private Cust custToReg = new Cust();
	private Map session;
	private Map root = new HashMap();
	private String REG_IMAGE_CODE;
	private MainService mainService;
	private static List<String> agent;
	static{
		try {
			agent = IOUtils.readLines(CustomerRegJson.class.getResourceAsStream("/agent.txt"), "GBK");
			for (ListIterator<String> iterator = agent.listIterator(); iterator.hasNext();) {
				String tmp = iterator.next();
				if (!StringUtils.hasText(tmp) || tmp.startsWith("#")) {
					iterator.remove();
				} else {
					iterator.set(tmp.trim());
				}
			}
		} catch (Exception e) {
			agent =  new ArrayList<String>();
			e.printStackTrace();
			logger.error("Cannot read agent.txt: "+e, e);
		}
		
	}

	public void validate() {
		try {
			{// 较验验证码
				String imgCode = (String) session.get(Constant.CAPTCHA_SESSION_HOLDER);
				if (!StringUtils.hasText(imgCode)) {
					addFieldError("REG_IMAGE_CODE", "请再次获取图片验证码");
					return;
				}

				if (!StringUtils.hasText(REG_IMAGE_CODE)) {
					addFieldError("REG_IMAGE_CODE", "请输入图片验证码");
					return;
				}
				if (!REG_IMAGE_CODE.toLowerCase().equals(imgCode)) {
					addFieldError("REG_IMAGE_CODE", "验证码输入错误");
					return;
				}
			}
			{// 验证生日
				String birth = custToReg.getCUST_BIRTHDAY();
				if (StringUtils.hasText(birth)) {
					try {
						SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
						sdf.parse(birth);
					} catch (Exception dateEx) {
						addFieldError("CUST_BIRTHDAY", "生日输入错误");
						return;
					}
				}
			}
			{// 验证mail是否被注册了
				mainService.validateEmailExist(this);
			}
			{// 验证手机号是否被注册了
				mainService.validateMobileExist(this);
			}

			{// 验证友邦营销员编号
				String free1 = custToReg.getCUST_FREETEXT1();
				if (StringUtils.hasText(free1)) {
					if (agent != null && agent.size() > 0 && !agent.contains(free1.trim())) {
						addFieldError("CUST_BIRTHDAY", "该营销员编号不存在");
						return;
					}
				}
			}

		} catch (Exception e) {
			addFieldError("SERVER_ERROR", "未知的较验错误");
			logger.error("validate()", e); //$NON-NLS-1$
			// throw new RuntimeException(e);
		}

	}

	/***
	 * nouse
	 */
	public String execute() {
		if (logger.isDebugEnabled()) {
			logger.debug("execute() - start"); //$NON-NLS-1$
		}
		try {
			getRoot().put("success", new Boolean(true));
			getRoot().put("message", "OK");

			unescapeCust(getCustToReg());

			mainService.insertCustByReg(this);

			{// 移除验证码session
				session.put(Constant.CAPTCHA_SESSION_HOLDER, "");
			}
			if (logger.isDebugEnabled()) {
				logger.debug("execute()"); //$NON-NLS-1$
			}
		} catch (Exception e) {
			logger.error("execute()", e); //$NON-NLS-1$
			getRoot().put("success", Boolean.FALSE);
			getRoot().put("message", "未知错误");
			return SUCCESS;
		}
		return SUCCESS;
	}

	public static void unescapeCust(Cust c) {
		if (logger.isDebugEnabled()) {
			logger.debug("unescapeCust(Cust) - start"); //$NON-NLS-1$

		}
		c.setCUST_NAME(Tools.unescapeTwice(c.getCUST_NAME()));
		if (logger.isDebugEnabled()) {
			logger.debug("unescapeCust(Cust)"); //$NON-NLS-1$
			logger.debug("unescapeCust(Cust)"); //$NON-NLS-1$
		}

		c.setCUST_SECURITY_Q(Tools.unescapeTwice(c.getCUST_SECURITY_Q()));
		c.setCUST_SECURITY_A(Tools.unescapeTwice(c.getCUST_SECURITY_A()));
		c.setCUST_PROVINCE(Tools.unescapeTwice(c.getCUST_PROVINCE()));
		c.setCUST_CITY(Tools.unescapeTwice(c.getCUST_CITY()));
		c.setCUST_COUNTY(Tools.unescapeTwice(c.getCUST_COUNTY()));
	}

	public Cust getModel() {
		return custToReg;
	}

	public void setCustToReg(Cust custToReg) {
		this.custToReg = custToReg;
	}

	public Cust getCustToReg() {
		return custToReg;
	}

	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}

	public void setRoot(Map root) {
		this.root = root;
	}

	public Map getRoot() {
		return root;
	}

	public void setREG_IMAGE_CODE(String rEG_IMAGE_CODE) {
		REG_IMAGE_CODE = rEG_IMAGE_CODE;
	}

	public String getREG_IMAGE_CODE() {
		return REG_IMAGE_CODE;
	}

	public void setMainService(MainService mainService) {
		this.mainService = mainService;
	}

	public MainService getMainService() {
		return mainService;
	}

}
